{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# SimpleImputer:处理数据中的缺失值",
   "id": "3b9de477b730047b"
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-02-27T14:46:31.650813Z",
     "start_time": "2025-02-27T14:46:31.647121Z"
    }
   },
   "source": [
    "from sklearn.impute import SimpleImputer\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "# 缺失值的处理方法：\n",
    "# 1. 丢弃缺失值\n",
    "# 2. 补全缺失值\n",
    "\n",
    "def im():\n",
    "    \"\"\"\n",
    "    缺失值处理\n",
    "    # numpy的数组中可以使用np.nan/np.NaN来代替缺失值，属于float类型\n",
    "    # 如果是文件中的一些缺失值，可以替换成nan，通过np.array转化成float型的数组即可\n",
    "\n",
    "    :return:NOne\n",
    "    \"\"\"\n",
    "    # NaN, nan,缺失值必须是这种形式，如果是？号(或者其他符号)，就要replace换成这种\n",
    "    # strategy: mean, median, most_frequent, constant，并且是形式为字符串\n",
    "    # im = SimpleImputer(missing_values=np.nan, strategy='mean')\n",
    "    # im = SimpleImputer(missing_values=np.nan, strategy='median')    # median更加保守，更适合处理中位数型数据\n",
    "    im = SimpleImputer(missing_values=np.nan, strategy='most_frequent') # 众数，出现次数最多的数值\n",
    "    # im = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=100)\n",
    "    \n",
    "    data = im.fit_transform([[1, 2],\n",
    "                             [np.nan, 3],\n",
    "                             [4, 6],\n",
    "                             [4, 2]])\n",
    "\n",
    "    print(data)\n",
    "\n",
    "    return None\n",
    "\n",
    "\n",
    "im()"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 2.]\n",
      " [4. 3.]\n",
      " [4. 6.]\n",
      " [4. 2.]]\n"
     ]
    }
   ],
   "execution_count": 12
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
